package cn.JHai.rbac.controller;


import cn.JHai.rbac.comm.LoginException;
import cn.JHai.rbac.comm.Result;
import cn.JHai.rbac.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class LoginController {

    @Autowired
    private EmployeeService employeeService;


    @PostMapping("/login")
    public Result login(String username, String password, boolean remember_me, HttpServletResponse response) {
        try {
            employeeService.login(username, password);
            if (remember_me) {
                Cookie cookie = new Cookie("login", username);
                System.out.println(cookie);
                response.addCookie(cookie);
            }
            return new Result(200l, "登陆成功");
        } catch (LoginException e) {
            e.printStackTrace();
            return new Result(500l, "用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(500l, "系统繁忙");
        }
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.removeAttribute("EMPLOYEE_SESSION");
        Cookie cookie = new Cookie("login", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        response.sendRedirect("/login.html");
    }
}
